//
//  ICListView.m
//  iCarStyle
//
//  Created by liu nian on 14-5-4.
//  Copyright (c) 2014年 liunian. All rights reserved.
//

#import "ICListView.h"
#import "PSCollectionView.h"
#import "ArticleCell.h"
#import "XTCollectionViewCell.h"
#import "SRRefreshView.h"
#import "RefreshCell.h"

#import "ArticleManager.h"

#define kIS_IOS7                (kCFCoreFoundationVersionNumber > kCFCoreFoundationVersionNumber_iOS_6_1)
@interface ICListView ()<UITableViewDelegate,UITableViewDataSource,PSCollectionViewDataSource,PSCollectionViewDelegate,RefreshCellDelegate, SRRefreshDelegate, UIScrollViewDelegate>{
    NSInteger   _pageNum;
}

@property (nonatomic) XTListViewType type;

@property (nonatomic , strong) UITableView *contentTableView;

@property (nonatomic , strong) PSCollectionView *contentCollectionView;

@property (nonatomic , strong) NSMutableArray *dataSource;
@property (nonatomic, assign) CatalogType    catalogType;
@property (nonatomic, assign) BOOL           isFirstRequest;
@property (nonatomic, strong) ReqObject     *objectReq;

@property(nonatomic, strong)SRRefreshView       *headRefreshView;
@property(nonatomic, strong)RefreshCell         *footRefreshView;

@end

@implementation ICListView

- (id)initWithFrame:(CGRect)frame
{
    return nil;
}

- (id)initWithFrame:(CGRect)frame type:(XTListViewType)type catalog:(CatalogType)catalogType
{
    if (self = [super initWithFrame:frame]) {

        _type = type;
        _pageNum = 1;
        _catalogType = catalogType;
        _dataSource = @[].mutableCopy;

        [self addContentView];
        self.mainList.delegate = self;
        [self showHeader:YES];
        [self showFooter:YES];

    }
    return self;
}

- (void)viewWillAppear{
    if (!self.dataSource.count)
        [self refreshData];
}

- (void)addContentView
{
    switch (_type) {
        case XTListViewTypeTableViewCell:
        {
        _contentTableView = ({
            UITableView *tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
            tableView.delegate = self;
            tableView.dataSource = self;
            [self addSubview:tableView];
            tableView;
        });
        break;
        }
        case XTListViewTypeCollectionCell:
        {
        _contentCollectionView = ({
            PSCollectionView *collectionView = [[PSCollectionView alloc] initWithFrame:self.bounds];
            collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
            collectionView.alwaysBounceVertical = YES;
            collectionView.numColsPortrait = 3;
            collectionView.collectionViewDataSource = self;
            collectionView.collectionViewDelegate = self;
            [self addSubview:collectionView];
            collectionView;
        });
        break;
        }
        default:
            break;
    }
}

- (UIScrollView*)mainList
{
    switch (_type) {
        case XTListViewTypeTableViewCell:
        {
        return self.contentTableView;
        break;
        }
        case XTListViewTypeCollectionCell:
        {
        return self.contentCollectionView;
        break;
        }
        default:
            break;
    }
}

- (ReqObject *)objectReq{
    return [[ReqObject alloc] initWithCatalogType:_catalogType pageNum:_pageNum];
}

- (void)reloadWithCatalog:(CatalogType)catalogType{
    _catalogType = catalogType;
    [self.headRefreshView setLoadingWithexpansion];
    [self refreshData];
}

- (void)reloadInputData{
    __weak typeof(self) weakSelf = self;
    if (_type == XTListViewTypeCollectionCell) {

        __weak typeof(PSCollectionView) *weakCollectionView = self.contentCollectionView;
        [[ArticleManager sharedManager] reloadPicListReqObject:self.objectReq itemsBlock:^(NSArray *items) {
            [weakSelf reloadListViewDataSource:items];
        } updateItemBlock:^(NSArray *items) {
            [weakCollectionView reloadData];
        }];

    }else{
        [[ArticleManager sharedManager] reloadNewsWithReqObject:self.objectReq itemsBlock:^(NSArray *items) {
            [weakSelf reloadListViewDataSource:items];
        }];
    }
}

- (void)reloadListViewDataSource:(NSArray *)array
{
    if (_pageNum == 1) {
        [self endHeaderRefreshState];
        [_dataSource removeAllObjects];
    }
    [self endFooterLoadState];

    [_dataSource addObjectsFromArray:array];

    if (_type == XTListViewTypeTableViewCell) {
        [self.contentTableView reloadData];
    }else if (_type == XTListViewTypeCollectionCell) {
        [self.contentCollectionView reloadData];
    }
}

- (void)configureCell:(ArticleCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    Article *article = [self.dataSource objectAtIndex:indexPath.row];
    [cell updateWithArticle:article];
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_dataSource.count) {
        return 2;
    }
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 && _dataSource.count) {
        return 1;
    }
    return (_dataSource.count - 1);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {

        //        id object = _dataSource[0];

        static NSString *CellIdentify = @"Cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentify];

        if (!cell) {

            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentify];

            cell.backgroundColor = [UIColor darkGrayColor];

            //            [cell setSeparatorInset:UIEdgeInsetsMake(0, 320, 0, -320)];
        }

        return cell;

    }else{
        static NSString *CellIdentify = @"XTCell";

        ArticleCell *cell = (ArticleCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentify];

        if (!cell) {

            cell = [[ArticleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentify];

            if (kIS_IOS7) {

                [cell setSeparatorInset:UIEdgeInsetsMake(0, 14, 0, 14)];
            }
        }

        [self configureCell:cell atIndexPath:indexPath];

        return cell;
    }
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 0;
    }
    return kHeightArticleCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return ;
    }
    Article *article = [self.dataSource objectAtIndex:indexPath.row];
    if (_delegate && [_delegate respondsToSelector:@selector(listView:didSelectArticle:atIndex:)]) {
        [_delegate listView:self didSelectArticle:article atIndex:indexPath.row];
    }
}

#pragma mark  PSCollectionViewDelegate
- (void)collectionView:(PSCollectionView *)collectionView didSelectCell:(PSCollectionViewCell *)cell atIndex:(NSInteger)index{
    PicModel *pic = [self.dataSource objectAtIndex:index];
    if (_delegate && [_delegate respondsToSelector:@selector(listView:didSelectPicModel:pictures:atIndex:)]) {
        [_delegate listView:self didSelectPicModel:pic pictures:self.dataSource atIndex:index];
    }
}
- (Class)collectionView:(PSCollectionView *)collectionView cellClassForRowAtIndex:(NSInteger)index{
    return [XTCollectionViewCell class];
}

#pragma mark - PSCollectionViewDataSource

- (NSInteger)numberOfRowsInCollectionView:(PSCollectionView *)collectionView{
    return _dataSource.count;
}

- (PSCollectionViewCell *)collectionView:(PSCollectionView *)collectionView cellForRowAtIndex:(NSInteger)index{
    XTCollectionViewCell *cell = (XTCollectionViewCell *)[collectionView dequeueReusableViewForClass:[XTCollectionViewCell class]];
    if (cell == nil) {
        cell = [[XTCollectionViewCell alloc] initWithFrame:CGRectMake(0, 0, kDefaultPictureCellWidth, kDefaultPictureCellHeight)];
    }
    PicModel *pic = [self.dataSource objectAtIndex:index];
    [cell collectionView:collectionView fillCellWithObject:pic atIndex:index];
    return cell;
}

- (CGFloat)collectionView:(PSCollectionView *)collectionView heightForRowAtIndex:(NSInteger)index{
    PicModel *pic = [self.dataSource objectAtIndex:index];
    return [XTCollectionViewCell rowHeightForObject:pic inColumnWidth:index];
}


- (void)loadMore
{
    _pageNum ++;
    [self reloadInputData];
}

- (void)refreshData
{
    _pageNum = 1;
    [self reloadInputData];
}

- (void)refreshCellDidTriggerLoading:(RefreshCell*)view
{
    [self loadMore];
}

- (void)slimeRefreshStartRefresh:(SRRefreshView*)refreshView
{
    [self refreshData];
}

- (BOOL)refreshCellDataSourceIsLoading:(RefreshCell*)view
{
    return _footRefreshView.state == RefreshLoading;
}

- (void)showHeader:(BOOL)bshow
{
    if(bshow)
        {
        if(!_headRefreshView)
            {
            [self headRefreshView];

            }
        [self.mainList addSubview:self.headRefreshView];
        }
    else
        {
        [_headRefreshView removeFromSuperview];
        RELEASE_SAFELY(_headRefreshView);
        }
}

- (void)showFooter:(BOOL)bshow
{
    if(bshow)
        {
        [self footRefreshView];
        }
    else
        {
        [_footRefreshView removeFromSuperview];
        RELEASE_SAFELY(_footRefreshView);
        }
}

- (void)endFooterLoadState
{
    if(_footRefreshView)
        {
        [_footRefreshView refreshScrollViewDataSourceDidFinishedLoading:self.mainList succeed:YES animal:NO];
        }
}

- (void)endHeaderRefreshState
{
    if(_headRefreshView)
        {
        [_headRefreshView endRefresh];
        }
}

#pragma mark  UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_headRefreshView scrollViewDidScroll];
    [_footRefreshView refreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_headRefreshView scrollViewDidEndDraging];
    [_footRefreshView refreshScrollViewDidEndDragging:scrollView];

}


- (RefreshCell *)footRefreshView
{
    if(!_footRefreshView)
        {
        _footRefreshView = [RefreshCell attachRefreshCellTo:self.mainList
                                                    delegate:self
                                              arrowImageName:@"refreshcell_img_arrow.png"
                                                   textColor:[UIColor darkGrayColor]
                                              indicatorStyle:UIActivityIndicatorViewStyleGray
                                                        type:RefreshTypeLoadMore];
        }
    return _footRefreshView;
}

- (SRRefreshView*)headRefreshView
{
    if(!_headRefreshView)
        {
        _headRefreshView = [[SRRefreshView alloc] init];
        _headRefreshView.delegate = self;
        _headRefreshView.upInset = 0;
        _headRefreshView.slimeMissWhenGoingBack = YES;
        _headRefreshView.slime.bodyColor = kPushRefreshBodyColor;
        _headRefreshView.slime.skinColor = kPushRefreshSkinColor;
        _headRefreshView.slime.lineWith = 1;
        }
    
    return _headRefreshView;
}
@end
